import { defineComponent, PropType } from 'vue'
import { useRegistry } from '../../hooks'
import { isStr, isPlainObj } from '@/shared'
import { IDesignerMiniLocales } from '@/core'

export const TextWidget = defineComponent({
  props: {
    title: {
      type: [String, Object] as PropType<string | IDesignerMiniLocales>,
      required: true,
    },
  },
  setup(props) {
    const registry = useRegistry()

    const takeLocale = (message: string | IDesignerMiniLocales) => {
      if (isStr(message)) return message
      if (isPlainObj(message)) {
        const lang = registry.getDesignerLanguage()
        for (let key in message) {
          if (key.toLocaleLowerCase() === lang) return message[key]
        }
        return
      }
      return message
    }

    const takeMessage = (token: any) => {
      if (!token) return
      const message = isStr(token) ? registry.getDesignerMessage(token) : token
      if (message) return takeLocale(message)
      return token
    }
    return () => <>{takeMessage(props.title)}</>
  },
})
